"""
库存管理相关API
"""
from flask import Blueprint, jsonify, request
from app.services.inventory_service import InventoryService
from app.utils.response import success_response, error_response
from app.utils.auth import require_auth
import logging

logger = logging.getLogger(__name__)
inventory_bp = Blueprint('inventory', __name__, url_prefix='/yonbip/scm')


@inventory_bp.route('/materialout/mergeSourceData/save', methods=['POST'])
@require_auth
def material_outbound_save():
    """材料出库保存 - 符合用友API规范"""
    try:
        request_data = request.get_json()

        # 验证顶层data对象
        if not request_data or 'data' not in request_data:
            return error_response("缺少data参数", code="400"), 400

        data = request_data['data']

        # 验证必要参数（根据API规范）
        required_fields = {
            'mergeSourceData': bool,
            '_status': str,
            'vouchdate': str,
            'bustype': str,
            'materOuts': list
        }

        for field, field_type in required_fields.items():
            if field not in data:
                return error_response(f"{field}不能为空", code="400"), 400
            if not isinstance(data[field], field_type):
                return error_response(f"{field}类型错误，期望{field_type.__name__}", code="400"), 400

        # 验证mergeSourceData必须为true
        if data['mergeSourceData'] is not True:
            return error_response("mergeSourceData必须为true", code="400"), 400

        # 验证_status必须为Insert
        if data['_status'] != 'Insert':
            return error_response("_status必须为Insert", code="400"), 400

        # 验证materOuts数组
        if not data['materOuts']:
            return error_response("materOuts不能为空数组", code="400"), 400

        # 验证每个materOuts项目的必要字段
        for i, mater_out in enumerate(data['materOuts']):
            required_mater_fields = ['makeRuleCode', 'sourceid', 'sourceautoid', '_status']
            for field in required_mater_fields:
                if field not in mater_out:
                    return error_response(f"materOuts[{i}].{field}不能为空", code="400"), 400

            if mater_out['_status'] != 'Insert':
                return error_response(f"materOuts[{i}]._status必须为Insert", code="400"), 400

        logger.info(f"材料出库申请: sourceid={data['materOuts'][0]['sourceid']}, materOuts_count={len(data['materOuts'])}")

        result = InventoryService.process_material_outbound(data)
        return success_response("出库申请提交成功", result)

    except ValueError as e:
        logger.error(f"材料出库参数错误: {str(e)}")
        return error_response(str(e), code="400"), 400
    except Exception as e:
        logger.error(f"材料出库异常: {str(e)}")
        return error_response(f"出库申请失败: {str(e)}"), 500


@inventory_bp.route('/stock/QueryCurrentStocksByCondition', methods=['POST'])
@require_auth
def query_current_stocks_by_condition():
    """现存量查询（用友标准接口）"""
    try:
        data = request.get_json()

        # 验证至少有一个查询条件
        if not data or not any([
            data.get('org'),
            data.get('warehouse'),
            data.get('warehouse.code'),
            data.get('product'),
            data.get('productn.code'),
            data.get('productsku'),
            data.get('productsku.code'),  # 新增：SKU编码查询
            data.get('batchno')
        ]):
            return jsonify({
                "code": "400",
                "message": "至少需要提供一个查询条件",
                "data": []
            }), 400

        logger.info(f"现存量查询: {data}")

        result = InventoryService.query_stocks_by_condition(data)

        return jsonify({
            "code": "200",
            "message": "操作成功",
            "data": result
        })

    except ValueError as e:
        logger.error(f"现存量查询参数错误: {str(e)}")
        return jsonify({
            "code": "400",
            "message": str(e),
            "data": []
        }), 400
    except Exception as e:
        logger.error(f"现存量查询异常: {str(e)}")
        return jsonify({
            "code": "500",
            "message": f"查询失败: {str(e)}",
            "data": []
        }), 500


@inventory_bp.route('/warehouse/inventory/list', methods=['GET'])
@require_auth
def inventory_query():
    """库存查询（旧接口，保留向后兼容）"""
    try:
        material_code = request.args.get('material_code')
        warehouse_id = request.args.get('warehouse_id')
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 20))

        logger.info(f"库存查询: material_code={material_code}, warehouse_id={warehouse_id}")

        result = InventoryService.query_inventory(material_code, warehouse_id, page, page_size)
        return success_response("查询成功", result)

    except Exception as e:
        logger.error(f"库存查询异常: {str(e)}")
        return error_response(f"库存查询失败: {str(e)}"), 500


@inventory_bp.route('/transaction/record', methods=['POST'])
@require_auth
def record_inventory_transaction():
    """记录库存流水"""
    try:
        data = request.get_json()

        # 验证必要参数
        required_fields = ['material_id', 'material_code', 'transaction_type', 'quantity']
        for field in required_fields:
            if not data.get(field):
                return error_response(f"{field}不能为空", code="400"), 400

        logger.info(f"记录库存流水: material={data['material_code']}, type={data['transaction_type']}, qty={data['quantity']}")

        result = InventoryService.record_inventory_transaction(data)
        return success_response("库存流水记录成功", result)

    except ValueError as e:
        logger.error(f"库存流水参数错误: {str(e)}")
        return error_response(str(e), code="400"), 400
    except Exception as e:
        logger.error(f"库存流水记录异常: {str(e)}")
        return error_response(f"库存流水记录失败: {str(e)}"), 500


@inventory_bp.route('/transaction/list', methods=['GET'])
@require_auth
def query_inventory_transactions():
    """查询库存流水记录"""
    try:
        # 获取查询参数
        query_params = {
            'page': int(request.args.get('page', 1)),
            'page_size': int(request.args.get('page_size', 20)),
            'material_code': request.args.get('material_code', ''),
            'warehouse_id': request.args.get('warehouse_id', ''),
            'transaction_type': request.args.get('transaction_type', ''),
            'start_date': request.args.get('start_date'),
            'end_date': request.args.get('end_date')
        }

        logger.info(f"查询库存流水: material_code={query_params['material_code']}, warehouse_id={query_params['warehouse_id']}")

        result = InventoryService.query_inventory_transactions(query_params)
        return success_response("查询成功", result)

    except Exception as e:
        logger.error(f"库存流水查询异常: {str(e)}")
        return error_response(f"库存流水查询失败: {str(e)}"), 500